//
//  SPRoutes.swift
//  PerfectTemplatePackageDescription
//
//  Created by John on 2018/6/5.
//

import Foundation
import PerfectLib
import PerfectHTTP
import PerfectMarkdown

//静态文本路由
public func makeLetRoutes() -> Routes{
    
    var routes = Routes()
    
    // 为程序接口API版本v1创建路由表
    var api = Routes()
    
    let markdown = "# 这是一个 markdown 文档 \n\n## with mojo 🇨🇳 🇨🇦"
    
    let html = markdown.markdownToHTML 
    
    //静态文本路由
    api.add(method: .get, uri: "/call1", handler: { _, response in
        response.setHeader(.contentType, value: "text/html")
        response.setBody(string: "API version v1 had used\(String(describing: html))")
        response.completed()
    })
    
    api.add(method: .get, uri: "/call2", handler: { _, response in
        response.setHeader(.contentType, value: "text/html")
        response.setBody(string: "Hello Everyone.This message is sending from YZWu.")
        response.completed()
    })
    
    api.add(method: .get, uri: "/call6") { (request, response) in
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "符合要求")
        response.completed()
    }
    
    // API版本v1
    var api1Routes = Routes(baseUri: "/v1")
    
    // API版本v2
    var api2Routes = Routes(baseUri: "/v2")
    
    // 为API版本v1增加主调函数
    api1Routes.add(api)
    
    // 为API版本v2增加主调函数
    api2Routes.add(api)
    
    // 更新API版本v2主调函数
    api2Routes.add(method: .get, uri: "/call2", handler: { _, response in
        response.setHeader(.contentType, value: "text/html")
        response.setBody(string: "API version v2 had used plan B ")
        response.completed()
    })
    
    // 将两个版本的内容都注册到服务器主路由表上
    routes.add(api1Routes)
    routes.add(api2Routes)
    
    return routes
    
}

//数据库
public func makeMySQLRoutes() -> Routes{
    var routes = Routes()
    
    routes.add(Route.init(methods: [.get,.post], uri: "/api/register", handler: UserRegister.requestHandler));
    return routes
}

//带变量路由路径
public func makeVarRoutes() -> Routes{
    var routes = Routes()
    
    let userName = "userName"
        
    routes.add(method: .get, uri: "/call3/{\(userName)}") { (request, response) in
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<html><title>Hello, world! </title><body>Hello, world!userName: \(String(describing: request.urlVariables[userName]))</body></html>")
        // Ensure that response.completed() is called when your processing is done.
        response.completed()
    }
    return routes
}

//通配路由
public func makeCommonRoutes() -> Routes{
    var routes = Routes()
    routes.add(method: .get, uri: "/call4/*/all") { (request, response) in
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<html><title>Hello, world! </title><body>call4 * all</body></html>")
        // Ensure that response.completed() is called when your processing is done.
        response.completed()
    }
    return routes
}

//结尾通配符路由
public func makeCommonEndRoutes() -> Routes{
    var routes = Routes()
    routes.add(method: .get, uri: "/call5/**") { (request, response) in
        let param = request.param(name:"message",defaultValue:"worry")
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<html><title>Hello, world! </title><body>call5 **\(String(describing: param))</body></html>")
        // Ensure that response.completed() is called when your processing is done.
        response.completed()
    }
    return routes
}

//文件上传
//MARK: - 文件上传

public func makeUploadFileRoutes() -> Routes{
    // 创建路径用于存储已上传文件
    let fileDir = Dir(Dir.workingDir.path + "files")
    do {
        try fileDir.create()
    } catch {
        print(error)
    }
    var routes = Routes()
    routes.add(method: .post, uri: "/upload") { (request, response) in
        // 通过操作fileUploads数组来掌握文件上传的情况
        // 如果这个POST请求不是分段multi-part类型，则该数组内容为空
        
        if let uploads = request.postFileUploads , uploads.count > 0 {
            // 创建一个字典数组用于检查已经上载的内容
            var ary = [[String:Any]]()
            
            for upload in uploads {
                ary.append([
                    "fieldName": upload.fieldName,  //字段名
                    "contentType": upload.contentType, //文件内容类型
                    "fileName": upload.fileName,    //文件名
                    "fileSize": upload.fileSize,    //文件尺寸
                    "tmpFileName": upload.tmpFileName   //上载后的临时文件名
                    ])
                // 将文件转移走，如果目标位置已经有同名文件则进行覆盖操作。
                let thisFile = File(upload.tmpFileName)
                do {
                    let _ = try thisFile.moveTo(path: fileDir.path + upload.fileName, overWrite: true)
                } catch {
                    print(error)
                }
                if upload.contentType == "xlsx"{
                    response.status = .ok
                }
                else{
                    response.status = .custom(code: 10086, message: "")
                    //                response.setBody(string: "文件格式不对body")
                    let code = "code",error = "error",message = "message"
                    
                    let scoreArray: [String:Any] = [code: 300, error: 230.45, message: 150]
                    
                    do{
                        let encoded = try scoreArray.jsonEncodedString()
                        try response.setBody(json: encoded)
                    }catch{
                        fatalError("\(error)")
                    }
                    
                }
            }
            
            response.completed()
        }
    }
    return routes
}
